import React, { Component } from "react";
import { connect } from "dva";
import {
  Input,
  Form,
  Select,
  Radio,
  DatePicker,
  Button,
  Row,
  Col,
  Checkbox,
  Icon
} from "antd";
import moment from "moment";
import { Editor } from "react-draft-wysiwyg";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import { EditorState, convertToRaw, ContentState } from "draft-js";
import draftToHtml from "draftjs-to-html";
import htmlToDraft from "html-to-draftjs";
import PushDescModal from "./PushDescModal";
import styles from "./PushRulesAdd.less";

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
const { RangePicker } = DatePicker;

@Form.create()
class PushRulesAdd extends Component {
  state = {
    validTime:
      this.props.dataSource &&
      this.props.dataSource.validTime &&
      this.props.dataSource.validTime.substring(0, 10), // 自定义的开始时间
    invalidTime:
      this.props.dataSource &&
      this.props.dataSource.invalidTime &&
      this.props.dataSource.invalidTime.substring(0, 10), // 自定义的结束时间
    ruleType: this.props.dataSource && this.props.dataSource.ruleType, // 推送类型的选择
    showDescModal: false,
    showEditor: false,
    editorState: EditorState.createEmpty()
  };

  // 加载下拉框数据
  componentDidMount() {
    const {
      dataSource: { appId, content, contentType } = {},
      dispatch
    } = this.props;
    dispatch({ type: "pushRules/staticDatas" });
    if (appId) {
      dispatch({
        type: "pushRules/getTrigger",
        payload: appId
      });
    }
    if (contentType === "news" && content) {
      this.setEditorState(content);
    }
  }

  /* 富文本编辑 */
  onEditorStateChange = editorState => {
    this.setState({
      editorState
    });
  };

  setEditorState = value => {
    const contentBlock = htmlToDraft(value);
    if (contentBlock) {
      const contentState = ContentState.createFromBlockArray(
        contentBlock.contentBlocks
      );
      const editorState = EditorState.createWithContent(contentState);
      this.setState({ editorState });
    }
  };

  // 提交
  handleOk = () => {
    // 校验表单
    this.props.form.validateFields((err, values = {}) => {
      // 表单校验规则不通过
      if (err) {
        return;
      }
      let temp = {};
      // 判断有效期是否是自定义
      if (values.effCycle === "diy") {
        temp = {
          validTime: this.state.validTime,
          invalidTime: this.state.invalidTime,
          effCycle: null
        };
      }
      // 判断有效期是否是无限
      if (values.effCycle === undefined) {
        temp = {
          validTime: null,
          invalidTime: null,
          effCycle: null
        };
      }
      let temp1 = {};
      // 判断是否为富文本编辑
      if (values.contentType === false) {
        temp1 = {
          contentType: "text",
          content: values.content
        };
      }
      if (values.contentType) {
        temp1 = {
          contentType: "news",
          content: draftToHtml(
            convertToRaw(this.state.editorState.getCurrentContent())
          )
        };
      }
      if (this.props.dataSource && this.props.dataSource.id) {
        // 编辑-提交
        const { id } = this.props.dataSource;
        const params = {
          ...values,
          ...temp,
          ...temp1,
          processClass: null,
          id
        };
        this.props.dispatch({
          type: "pushRules/pushRuleConfMod",
          payload: params
        });
      } else {
        // 添加-提交 创建者暂定为空
        const params = {
          ...values,
          ...temp,
          triggerTime: "1",
          status: "1",
          ...temp1,
          processClass: null
        };
        this.props.dispatch({
          type: "pushRules/pushRuleConfAdd",
          payload: params
        });
      }
    });
  };

  // 日期选择器Change事件
  onRangePickerChange = values => {
    this.setState({
      validTime: values[0] ? values[0].format("YYYY-MM-DD") : null,
      invalidTime: values[1] ? values[1].format("YYYY-MM-DD") : null
    });
  };

  render() {
    const {
      getFieldDecorator,
      setFieldsValue,
      getFieldValue
    } = this.props.form;
    const { dataSource = {}, closeModal, pushRules = {} } = this.props;
    const { staticDatas } = pushRules;
    const { pushAppList = [], triggerList = [], sceneList = [] } = staticDatas;
    const { showDescModal } = this.state;
    const {
      ruleName,
      sceneId,
      appId,
      content,
      contentType,
      opTypeId,
      comment,
      validTime,
      id,
      invalidTime
    } = dataSource;
    const showEditor = getFieldValue("contentType");
    const appOption = pushAppList.map(item => (
      <Option key={item.id} value={item.id}>
        {item.appName}
      </Option>
    ));
    const opTypeOption = triggerList.map(item => (
      <Option key={item.id} value={item.id}>
        {item.trigger}
      </Option>
    ));
    const sceneOption = sceneList.map(item => (
      <Option key={item.id} value={item.id}>
        {item.name}
      </Option>
    ));
    return (
      <div className={styles.root}>
        <div className={styles.title}>{id ? "编辑规则" : "新增规则"}</div>
        <Form layout="inline">
          <Row>
            <Col span={24}>
              <FormItem label={"规则名称"} className={styles.selectTitle}>
                {getFieldDecorator("ruleName", {
                  rules: [
                    {
                      required: true,
                      message: "请输入规则名称!"
                    },
                    {
                      pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
                      message: "规则名称含非法字符!"
                    }
                  ],
                  initialValue: ruleName
                })(<Input placeholder="请输入" style={{ width: 850 }} />)}
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem label={"推送场景"} className={styles.selectTitle}>
                {getFieldDecorator("sceneId", {
                  rules: [
                    {
                      required: true,
                      message: "请选择推送场景!"
                    }
                  ],
                  initialValue: sceneId
                })(
                  <Select
                    onChange={e => {
                      this.setState({ sceneId: e });
                    }}
                    placeholder="请选择"
                    style={{ width: 240 }}
                  >
                    {sceneOption}
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem label={"推送应用"} className={styles.selectTitle}>
                {getFieldDecorator("appId", {
                  rules: [
                    {
                      required: true,
                      message: "请选择推送应用!"
                    }
                  ],
                  initialValue: appId
                })(
                  <Select
                    onChange={value => {
                      this.props.form.setFieldsValue({ opTypeId: undefined });
                      this.props.dispatch({
                        type: "pushRules/getTrigger",
                        payload: value
                      });
                    }}
                    placeholder="请选择"
                    style={{ width: 240 }}
                  >
                    {appOption}
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem label={"触发动作"} className={styles.selectTitle}>
                {getFieldDecorator("opTypeId", {
                  rules: [
                    {
                      required: true,
                      message: "请选择触发动作!"
                    }
                  ],
                  initialValue: opTypeId ? Number(opTypeId) : undefined
                })(
                  <Select
                    onChange={e => {
                      this.setState({ opTypeId: e });
                    }}
                    placeholder="请选择"
                    style={{ width: 240 }}
                  >
                    {opTypeOption}
                  </Select>
                )}
              </FormItem>
            </Col>
            {/*  <FormItem label={'规则类型'} className={styles.selectTitle}>
            {getFieldDecorator('ruleType', {
              rules: [
                {
                  required: true,
                  message: '请选择规则类型!'
                }
              ],
              initialValue: ruleType
            })(
              // TODO：提示文字失效
              <Select
                onChange={e => {
                  this.setState({ ruleType: e });
                }}
                placeholder="请选择"
                style={{ width: 240 }}
              >
                {optionData.map((item, index) => (
                  <Option key={index} value={item.val}>
                    {item.title}
                  </Option>
                ))}
              </Select>
            )}
          </FormItem> */}
            <Col span={24}>
              {(() => {
                if (showEditor === true) {
                  return (
                    <FormItem label={"推送内容"} className={styles.selectTitle}>
                      {getFieldDecorator("wysiwygcontent", {
                        rules: [
                          {
                            required: true,
                            message: "请输入推送内容!"
                          }
                        ]
                      })(
                        <Editor
                          editorState={this.state.editorState}
                          toolbarClassName={styles.editorToolbar}
                          editorClassName={styles.editorContent}
                          onEditorStateChange={this.onEditorStateChange}
                        />
                      )}
                    </FormItem>
                  );
                }
                return (
                  <FormItem label={"推送内容"} className={styles.selectTitle}>
                    {getFieldDecorator("content", {
                      rules: [
                        {
                          required: true,
                          message: "请输入推送内容!"
                        }
                      ],
                      initialValue: content
                    })(
                      <TextArea
                        placeholder="示例：'{$Name}'的身份证号码是'{$Card_ID}'，手机号码是'{$Tle_phone}'"
                        rows={4}
                        cols={120}
                        maxLength={3000}
                        style={{ width: 850 }}
                      />
                    )}
                  </FormItem>
                );
              })()}
            </Col>
            <Col span={24}>
              <FormItem label=" " colon={false} className={styles.selectTitle}>
                <div style={{ width: 850 }}>
                  {getFieldDecorator("contentType", {
                    initialValue: contentType === "news",
                    valuePropName: "checked"
                  })(<Checkbox>图文内容</Checkbox>)}
                  <a
                    className={styles.explain}
                    onClick={() => {
                      this.setState({
                        showDescModal: true
                      });
                    }}
                  >
                    <Icon type="info-circle-o" />
                    说明
                  </a>
                </div>
              </FormItem>
            </Col>
            <Col span={24}>
              <FormItem label={"规则说明"} className={styles.selectTitle}>
                {getFieldDecorator("comment", {
                  rules: [
                    {
                      required: true,
                      message: "请输入规则说明!"
                    }
                  ],
                  initialValue: comment
                })(
                  <TextArea
                    placeholder="不超过300个字符"
                    rows={4}
                    cols={120}
                    maxLength={300}
                    style={{ width: 850 }}
                  />
                )}
              </FormItem>
            </Col>
            {/*  {this.state.ruleType === '精准推送' && (
              <FormItem label={'推送用户'} className={styles.selectTitle}>
                // TODO：推送用户暂时是下一个版本的功能 
                <Select mode="multiple" style={{ width: 425 }}>
                  <Option key={1} value={'用户1'}>
                    用户1
                  </Option>
                  <Option key={2} value={'用户2'}>
                    用户2
                  </Option>
                  <Option key={3} value={'用户3'}>
                    用户3
                  </Option>
                </Select>
              </FormItem>
            )} */}
            <Col span={24}>
              <FormItem label={"规则有效期"} className={styles.selectTitle}>
                {getFieldDecorator("effCycle", {
                  initialValue: validTime ? "diy" : undefined
                })(
                  <RadioGroup style={{ width: 440 }}>
                    <Radio value={undefined}>不限</Radio>
                    <Radio value="year">1年有效</Radio>
                    <Radio value="month">1月有效</Radio>
                    <Radio value="week">1周有效</Radio>
                    <Radio value="day">当天有效</Radio>
                    <Radio value="diy">
                      自定义
                      {
                        <RangePicker
                          defaultValue={
                            validTime
                              ? [moment(validTime), moment(invalidTime)]
                              : []
                          }
                          style={{ marginLeft: 15, width: 200 }}
                          className={styles.pocker}
                          format="YYYY-MM-DD"
                          onChange={value => {
                            this.onRangePickerChange(value);
                            setFieldsValue({ effCycle: "diy" });
                          }}
                        />
                      }
                    </Radio>
                  </RadioGroup>
                )}
              </FormItem>
            </Col>
            {/* 暂时不用关联模板 */}
            {/* <Col span={12}>
              <FormItem label={"消息模板"} className={styles.selectTitle}>
                {getFieldDecorator("templateId", {
                  rules: [
                    {
                      required: true,
                      message: "请选择触发动作!"
                    }
                  ],
                  initialValue: templateId
                })(
                  <Select
                    onChange={e => {
                      this.setState({ templateId: e });
                    }}
                    placeholder="请选择"
                    style={{ width: 240 }}
                  >
                    {optionData.map((item, index) => (
                      <Option key={index} value={item.val}>
                        {item.title}
                      </Option>
                    ))}
                  </Select>
                )}
              </FormItem>
            </Col> */}
          </Row>
        </Form>
        <PushDescModal
          showDescModal={showDescModal}
          onCancel={() => {
            this.setState({
              showDescModal: false
            });
          }}
        />
        <div className={styles.btnGroup}>
          <Button onClick={closeModal}>取消</Button>
          <Button type="primary" onClick={this.handleOk}>
            保存
          </Button>
        </div>
      </div>
    );
  }
}

export default connect(stores => ({
  pushRules: stores.pushRules
}))(PushRulesAdd);
